//
//  MusicManager.m
//  老司机发车了
//
//  Created by SuperNing on 16/8/9.
//  Copyright © 2016年 斌. All rights reserved.
//

#import "MusicManager.h"

#import "DetailListModel.h"
#import "PlayerModel.h"
#import "MusicDownload.h"
#import "MusicDataBase.h"

@interface MusicManager ()

@property(nonatomic, strong) AVPlayer *player;


@property (nonatomic, strong)NSTimer *timer;


@end

static MusicManager *_musicManager = nil;
@implementation MusicManager

+ (instancetype)shareMusicManager{
    
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _musicManager = [[MusicManager alloc] init];
        [[NSNotificationCenter defaultCenter] addObserver:_musicManager selector:@selector(playNextSong) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
        // 打开数据库
        [[MusicDataBase shareMusicDataBase] openDB];
        // 建表
        [[MusicDataBase shareMusicDataBase] createTableWithTableName:@"musicTable"];
        
    });
    return _musicManager;
}


- (instancetype)init{
    
    if (self = [super init]) {
        _player = [[AVPlayer alloc] init];

    }
    return self;
}


- (void)loadSongInfo{
    
    DetailListModel *detaillistmodel = _musicArray[_index];
    NSString *songUrl = [NSString stringWithFormat:@"%@%@%@",songInfoOne_Url,detaillistmodel.song_id,songInfoTwo_Url];
    
    [NetWorkRequestManager requestWithType:GET urlString:songUrl parDic:@{} finish:^(NSData *data) {
    
        NSDictionary *dataDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

        
        NSDictionary *dict1 = dataDic[@"songinfo"];
        
        NSMutableArray *mArr = dataDic[@"songurl"][@"url"];
        NSDictionary *dict2 = mArr[0];
        PlayerModel *model = [[PlayerModel alloc] init];
        [model setValuesForKeysWithDictionary:dict1];
        [model setValuesForKeysWithDictionary:dict2];
        self.playerModel = model;
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"loadData" object:nil];
        
        [[MusicDataBase shareMusicDataBase] insertDataWithModel:self.playerModel];
        
        [self playMusic:self.playerModel.file_link];
        
    } finishError:^(NSError *error) {
        
    }];
    
    
}

- (void)playMusic:(NSString *)fileLink{
    
    if (_playerItem) {
        
        [_playerItem removeObserver:self forKeyPath:@"status"];
    }
    _playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:fileLink]];
    
    [_playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
    [_player replaceCurrentItemWithPlayerItem:_playerItem];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    
    switch ([change[@"new"] integerValue]) {
        case AVPlayerItemStatusFailed:
            NSLog(@"歌曲缓冲失败");
            break;
            case AVPlayerStatusReadyToPlay:
            NSLog(@"歌曲缓冲成功");
            _isPlay = YES;
            // 播放歌曲
            [self startPlayMusic];
            
            break;
            case AVPlayerStatusUnknown:
            NSLog(@"缓冲状态未知");
        default:
            break;
    }
    
}

- (void)timeAction{
    
    float progress = (float)_playerItem.currentTime.value / _playerItem.currentTime.timescale;
    
    [self.delegate autoRefreshProgress:progress];
    
    
}

- (void)seekToTime:(float)progress{
    [_player seekToTime:CMTimeMakeWithSeconds((Float64)progress, (int32_t)_playerItem.currentTime.timescale)];
    
}


- (void)startPlayMusic{
    
    if (_isPlay == YES) {
        [_timer invalidate];
        _timer = [NSTimer scheduledTimerWithTimeInterval:0.05 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
        [_player play];
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"isPlay" object:nil];
}

- (void)stopPlayMusic{
    
    [_timer invalidate];
    [_player pause];
    _isPlay = NO;
    [[NSNotificationCenter defaultCenter] postNotificationName:@"isPlay" object:nil];
}

- (void)previousMusic{
    if (_index == 0) {
        _index = _musicArray.count - 1;
    }else{
        _index = _index - 1;
    }
    [self loadSongInfo];
}

- (void)nextMusic{
    if (_index == _musicArray.count - 1) {
        _index = 0;
    }else{
        _index = _index + 1;
    }
    [self loadSongInfo];
}

// 由下载功能改为喜欢
- (void)downloadMusic{
    if (_playerModel) {

        // 打开数据库
        [[MusicDataBase shareMusicDataBase] openDB];
        // 建表
        [[MusicDataBase shareMusicDataBase] createTableWithTableName:@"loveTable"];
        
        [[MusicDataBase shareMusicDataBase] insertDataWithModel:_playerModel];

    }
}

- (void)playNextSong{
    switch (_playStyle) {
        case 0:
            [self playRound];
            break;
           case 1:
            [self playSingle];
            break;
            case 2:
            [self playRandom];
            break;
            case 3:
            [self playOrder];
            break;
        default:
            break;
    }
    
}

- (void)playSingle{
    [self playMusic:_playerModel.file_link];
}

- (void)playOrder{
    if (_index == _musicArray.count - 1) {
        [_player pause];
        [_timer invalidate];
    } else {
        _index = _index + 1;
        [self loadSongInfo];
    }
}
- (void)playRound{
    _index =  (_index == _musicArray.count - 1) ? 0 : _index + 1;
    [self loadSongInfo];
}

- (void)playRandom{
    NSInteger tempIndex = arc4random_uniform((UInt32)_musicArray.count);
    _index = tempIndex;
    [self loadSongInfo];
}










@end
